package com.lw.leetcode.other.b;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * 6005. 使数组变成交替数组的最少操作数
 * 2170. 使数组变成交替数组的最少操作数
 *
 * @author liw
 * @version 1.0
 * @date 2022/2/13 22:26
 */
public class MinimumOperations {

    public static void main(String[] args) {
        MinimumOperations test = new MinimumOperations();


        // 3
//        int[] arr = {3,1,3,2,4,3};

        // 2
//        int[] arr = {1,1,1,1,1};

        // 2
        int[] arr = {1,2,2,2,2};

        int i = test.minimumOperations(arr);
        System.out.println(i);
    }

    public int minimumOperations(int[] nums) {
        int length = nums.length;
        Map<Integer, Integer> a = new HashMap<>();
        Map<Integer, Integer> b = new HashMap<>();
        int n2 = length >> 1;
        int n1 = length - n2;
        for (int i = 0; i < length; i += 2) {
            a.put(nums[i], a.getOrDefault(nums[i], 0) + 1);
            if (i != length - 1) {
                b.put(nums[i + 1], b.getOrDefault(nums[i + 1], 0) + 1);
            }
        }
        int max1 = 0;
        for (Map.Entry<Integer, Integer> entry : a.entrySet()) {

            max1 = Math.max(max1, entry.getValue());
        }
        int max2 = 0;
        for (Map.Entry<Integer, Integer> entry : b.entrySet()) {
            max2 = Math.max(max2, entry.getValue());
        }
        Set<Integer> key1 = new HashSet<>();
        for (Map.Entry<Integer, Integer> entry : a.entrySet()) {
            if (entry.getValue() == max1) {
                key1.add(entry.getKey());
            }
        }
        Set<Integer> key2 = new HashSet<>();
        for (Map.Entry<Integer, Integer> entry : b.entrySet()) {
            if (entry.getValue() == max2) {
                key2.add(entry.getKey());
            }
        }
        key1.addAll(key2);
        if (key1.size() == 1) {
            int c1 = 0;
            for (Map.Entry<Integer, Integer> entry : a.entrySet()) {
                int v = entry.getValue();
                if (v != max1 && v > c1) {
                    c1 = v;
                }
            }
            int c2 = 0;
            for (Map.Entry<Integer, Integer> entry : b.entrySet()) {
                int v = entry.getValue();
                if (v != max2 && v > c2) {
                    c2 = v;
                }
            }
            return Math.min(n1 - max1 + n2 - c2, n1 - c1 + n2 - max2);
        }
        return n1 - max1 + n2 - max2;
    }

}
